import { useAntdTable } from 'ahooks';
import { Button, Card, Descriptions, Divider, message, Row, Typography } from 'antd';
import React, { useState } from 'react';
import SlickTable from '@/components/SlickTable';
import request from '@/utils/request';
import Space from '@/components/Space';
import useModal from '@/hooks/UseModal';
import AddUserModal from './AddUserModal';

const { Item } = Descriptions;
const { Text } = Typography;

function fetchUsers({ current, pageSize, tenantId }) {
  return request.post('/tenant/pageUsersWithTenantId', {
    data: {
      current,
      pageSize,
      tenantId,
    },
  });
}

function TenantDetail({ record, goToStep }) {
  const { tenantId } = record;
  const {
    tableProps: { loading, ...restTableProps },
    refresh,
  } = useAntdTable(query => fetchUsers({ ...query, tenantId }), {
    defaultPageSize: 10,
  });

  const { visible, hideModal, showModal } = useModal();
  const [mask, setMask] = useState(false);

  const removeRelation = userId => {
    setMask(true);
    request
      .post(`/tenant/removeRelation?userId=${userId}&tenantId=${tenantId}`)
      .then(() => {
        message.success('取消成功');
        refresh();
      })
      .finally(() => setMask(false));
  };

  const columns = [
    {
      title: '用户ID',
      dataIndex: 'userId',
    },
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '操作',
      width: 300,
      render: (_, record) => (
        <Space divider="vertical">
          <a onClick={() => removeRelation(record.userId)}>取消关联</a>
        </Space>
      ),
    },
  ];

  return (
    <Card
      title="租户详情"
      bodyStyle={{ padding: '16px 16px 128px 32px' }}
      extra={
        <Button type="primary" onClick={() => goToStep(1)}>
          返回
        </Button>
      }
    >
      <div className="ant-detail-title">基本信息</div>
      <Descriptions column={4}>
        <Item label="租户ID">{record.tenantId}</Item>
        <Item label="租户名称">{record.tenantName}</Item>
        <Item label="租户编码">{record.tenantCode}</Item>
        <Item label="HTTP数据源URL前缀">{record.httpDataSourceUrlPrefix}</Item>
        <Item label="ACCESS_KEY">
          <Text copyable>{record.accessKey}</Text>
        </Item>
      </Descriptions>
      <Divider />
      <Row className="margin-bottom" type="flex" justify="space-between" align="middle">
        <div className="ant-detail-title" style={{ marginBottom: 0 }}>
          用户列表
        </div>
        <Button type="primary" icon="plus" onClick={showModal}>
          添加用户
        </Button>
      </Row>
      <SlickTable loading={mask || loading} rowKey="userId" columns={columns} {...restTableProps} />
      {visible && (
        <AddUserModal
          tenantId={tenantId}
          onCancel={hideModal}
          onOk={() => {
            hideModal();
            refresh();
          }}
        />
      )}
    </Card>
  );
}

export default TenantDetail;
